#!/usr/bin/env python3
# encoding=utf-8

import os
import shutil
import fitz
import with_win32 as wwin32
from zipfile import ZipFile
from docx2pdf import convert

import logging
logger = logging.getLogger(__name__)

def replace_word_png(wordpath, image):
    if not os.path.exists(wordpath):
        logger.error(f'replace_word_png {wordpath} not exit')
        return
    if not os.path.exists(image):
        logger.error(f'replace_word_png {image} not exit')
        return
    new_zip_path = wordpath.replace('.docx', '.zip')
    # 打开.docx文件作为zip文件处理
    with ZipFile(wordpath, 'r') as z:
        with ZipFile(new_zip_path, 'w') as new_zip_ref:
            for file in z.filelist:
                if file.filename.endswith(".png"):
                    rpng = file.filename
                    with open(image, 'rb') as new_img_file:
                        file_data = new_img_file.read()
                    # continue
                else:
                    file_data = z.read(file)
                # print(file.filename)
                new_zip_ref.writestr(file, file_data)
            # print("last " + rpng)
    shutil.copy(new_zip_path, wordpath)
    os.remove(new_zip_path)
    os.remove(image)
    logging.info(f'replace word image pass {image}')

def word_to_pdf(wordpath, pdfpath):
    if not os.path.exists(wordpath):
        return
    try:
        with wwin32.Win32AppManager(wordpath) as (word, doc):
            # doc.ExportAsFixedFormat(pdfpath, 17)  # 17 表示 PDF 格式
            doc.ExportAsFixedFormat(
                OutputFileName=pdfpath, 
                ExportFormat=1,  # 0=PDF，1=图片
                Dpi=300,         # 图片 DPI
                Combine2LongPic=False  # 是否合并为长图
            )
    except Exception as e:
        logging.error(f"myword pdf error[{e}]")
        wwin32.kill_word_process()  # 兜底清理
        
def pdf_to_img(pdfpath, imgpath, clip_rect):
    if not os.path.exists(pdfpath):
        return
    dpi = 600
    pdf = fitz.open(pdfpath)
    page = pdf.load_page(0)  # 加载第一页
    # 整个页面出图
    # pix = page.get_pixmap(dpi=dpi)  # 设置分辨率

    # 生成高分辨率图片
    zoom = dpi / 72  # 计算缩放因子（72点为1英寸）
    matrix = fitz.Matrix(zoom, zoom)  # 缩放矩阵
    pix = page.get_pixmap(matrix=matrix, clip=clip_rect)  # 渲染指定区域

    # 保存为 PNG 或 JPG
    if imgpath.lower().endswith(".jpg"):
        pix.save(imgpath, "jpg")  # 调整 quality 控制压缩率
    else:
        pix.save(imgpath)
    pdf.close()
        
def word_to_image(wordpath, rect):
    basename = wordpath.split('.doc')[0]
    pdfpath = basename + '.pdf'
    try:
        convert(wordpath, pdfpath)
    except Exception as e:
        logging.error(f"myword convert pdf error[{e}]")
        return
    # word_to_pdf(wordpath, pdfpath)
    imgpath = basename + '.jpg'
    pdf_to_img(pdfpath, imgpath, tuple(rect))
    logging.info(f'word to image pass {os.path.basename(imgpath)}')
    if os.path.exists(pdfpath):
        os.remove(pdfpath)
        
